package com.pinc.cpbl;

import java.io.InputStream;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class show_rank extends WidgetActivity {
	private ListView lv;
	private ShowRankTask mTask;
	private int mLeague;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_layout);
		initWidget();
		mLeague = 0;
		mTask = new ShowRankTask();
		mTask.execute(getApplicationContext());
	}

	@Override
	protected void initUpbar() {
		tv_title.setText(R.string.title_team_rank);

		b_right.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mTask = new ShowRankTask();
				mTask.execute(show_rank.this);
				loadAD();
			}
		});

		b_right2.setVisibility(View.VISIBLE);
		b_right2.setText(getResources().getString(R.string.str_league2));
		b_right2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mLeague = 1-mLeague;
				mTask = new ShowRankTask();
				mTask.execute(show_rank.this);
				loadAD();
			}
		});
	}

	@Override
	protected void initWidget() {
		super.initWidget();
		lv = (ListView)findViewById(R.id.listView1);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mTask.cancel(true);
	}

	private class ShowRankTask extends AsyncTask<Context, Void, Integer> {
		private RankItem_Adapter rank_items;

		protected Integer doInBackground(Context... ctx) {
			if (isNoInternet())
				return comn_param.ERR_ID_NO_NETWORK;

			rank_items = new RankItem_Adapter(ctx[0]);
			try {
				InputStream is = MyHTTPHelper.ConnectURL(comn_param.CPBL_URL);
				if ( is == null)
					return comn_param.ERR_ID_TIMEOUT;

				Parser_Rank mp = new Parser_Rank(is);
				mp.stream.skip(8000);
				String strLeague;
				if ( mLeague == 0)
					strLeague = "lblR1";
				else
					strLeague = "lblR2";
				mp.gotoTagByProp("span", "id", strLeague);
				mp.nextTag();
				mp.parse(rank_items);
			}
			catch(Exception e)
			{
				return comn_param.ERR_ID_UNKNOWN;
			}
			return comn_param.ID_SKIP;
		}

		@Override
		protected void onPreExecute() {
			b_right.setVisibility(View.INVISIBLE);
			b_right2.setVisibility(View.INVISIBLE);
			mProgbar.setVisibility(View.VISIBLE);
			lv.setAdapter(null);
		}

		protected void onPostExecute(Integer err) {
			b_right.setVisibility(View.VISIBLE);
			b_right2.setVisibility(View.VISIBLE);
			if ( mLeague == 0)
				b_right2.setText(getResources().getString(R.string.str_league2));
			else
				b_right2.setText(getResources().getString(R.string.str_league1));
			mProgbar.setVisibility(View.INVISIBLE);

			showDialogCompat(err);
			lv.setAdapter(rank_items);
		}
	}

}
